package com.xiehua.task.job.miscellaneous;

import redis.clients.jedis.Jedis;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static com.xiehua.task.prop.XiehuaConfig.REVISE_TIME;

public class EmailMemorandum {

    private Jedis jedis;

    public static final String KEY_EMAIL_COUNT_PIX = "email_count_flag";

    public static final String KEY_EMAIL_MONITOR_SWITCH_PIX = "email_monitor_switch_";

    public static final String KEY_EMAIL_SEND_PIX = "email_send_";

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public EmailMemorandum(Jedis jedis) {
        this.jedis = jedis;
    }

    /***
     * 写入一个邮件发送标志位
     * **/
    public void writeFlagEmailCount() {
        String key = KEY_EMAIL_COUNT_PIX + LocalDateTime.now().getHour();
        jedis.setex(key, 60 * 60 - REVISE_TIME , Boolean.TRUE.toString());
    }

    /***
     * 读取一个邮件发送标志位
     * **/
    public boolean existFlagEmalCount() {
        String key = KEY_EMAIL_COUNT_PIX + LocalDateTime.now().getHour();
        return jedis.exists(key);
    }

    /**
     * 主题监控开关
     * **/
    public void topicMonitorSwitch(String topic,Boolean flag){
        String key = KEY_EMAIL_MONITOR_SWITCH_PIX + topic;
        jedis.set(key, flag.toString());
    }

    /**
     * 查询主题监控开关
     * **/
    public Boolean queryTopicMonitorSwitch(String topic){
        String key = KEY_EMAIL_MONITOR_SWITCH_PIX + topic;
        if(!jedis.exists(key)) return true;
        return Boolean.parseBoolean(jedis.get(key));
    }

    /**
     * 写入邮件发送时间
     * **/
    public void sendEmail(String topic){
        String key = KEY_EMAIL_SEND_PIX + topic;
        String value = LocalDateTime.now().format(formatter);
        jedis.setex(key, 60 * 60 - REVISE_TIME, value);
    }

    /**
     * 读取邮件上次发送时间
     * **/
    public Boolean checkSendEmailRate(String topic){
        String key = KEY_EMAIL_SEND_PIX + topic;
        if(jedis.exists(key)) return true;
        return false;
    }


}
